package com.jae.service.impl;


import com.jae.mapper.*;
import com.jae.model.resc.Resc;
import com.jae.model.role.Role;
import com.jae.model.role.RoleDTO;
import com.jae.model.roleResc.RoleResc;
import com.jae.model.user.User;
import com.jae.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private RoleRescMapper roleRescMapper;
	@Autowired
	private RescMapper rescMapper;
	
	/**
	* 	获取所有角色	
	*/
	@Override
	public List<RoleDTO> findAll(Map map) {
		return roleMapper.findAll(map);
	}
	
	/**
	* 	获取一条角色	
	*/
	@Override
	public RoleDTO findOne(Map map) {
		return roleMapper.findOne(map);
	}
	
	/**
	* 	根据ID获取角色	
	*/
	@Override
	public RoleDTO findById(Integer role_id) {
		Role role = new Role();
		role.setRole_id(role_id);
	
		return roleMapper.findById(role);
	}
	
	
	
	/**
	 * 新增角色
	 */
	@Override
	public boolean insert(Role role, User user) throws Exception {
		role.setCreated_time(new Date());
		if(roleMapper.insert(role)!=1)
			serviceError("插入失败");

		List<RoleResc> rrList = new ArrayList<RoleResc>();
		//查找所有的默认权限
		List<Resc> rList = rescMapper.findAllDefault();
		for (Resc r : rList) {
			RoleResc roleResc = new RoleResc();
			roleResc.setResc_id(r.getResc_id());
			roleResc.setRole_id(role.getRole_id());
			rrList.add(roleResc);
		}
		if(rrList.size()>0)
			roleRescMapper.insertBatch(rrList);
		
		return true;
	}
	
	/**
	 * 修改角色
	 */
	@Override
	public boolean update(Role role, User user){
		if(roleMapper.update(role)!=1)
			serviceError("修改失败");
		return true;
	}
	
	
	/**
	 * 	逻辑删除角色
	 */
	@Override
	public boolean updateDelete(Integer role_id, User user){
		Role old=new Role();
		//role.setLast_updated_by(user.getUser_id());
		//role.setLast_updated_date(new Date());
		old.setRole_id(role_id);
		
		if(roleMapper.updateDelete(old)!=1)
			serviceError("逻辑删除失败");
		return true;
	}
	
	/**
	 * 	物理删除角色
	 */
	@Override
	public boolean delete(Integer role_id){
		//删除userRole
		userRoleMapper.deleteByRoleId(role_id);
		
		//删除roleResc
		roleRescMapper.deleteByRoleId(role_id);
		Role old = new Role();
		old.setRole_id(role_id);
		if(roleMapper.delete(old)!=1)
			serviceError("删除失败");
		return true;
	}


	@Override
	public List<String> findByResc(Long resc_id) {
		// TODO Auto-generated method stub
		return null;
	}
	
}